package com.controllor;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dao.HumanDao;
import com.dao.LoginDao;
import com.entity.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public LoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String userid = request.getParameter("userid");
		String pwd = request.getParameter("pwd");

		System.out.println("userid pwd:"+userid+pwd);
		Map<String,String> map = new HashMap<String,String>();
		HttpSession session = request.getSession();
		User user = null;
		user = LoginDao.logincheck(userid,pwd);
		if(user != null) {
			map.put("msg", "1");
			session.setAttribute("user", user);
			String dept = user.getDeptid();
			String role = user.getRoleid();
			//依据身份，跳转不同
			if("1".equals(dept)) {//人力部
				map.put("url", "humanIndex.jsp");
			}else if("52".equals(dept)) {//财务部
				map.put("url", "financeIndex.jsp");
			}else if("1".equals(role)) {//经理
				map.put("url", "managerIndex.jsp");
//				session.setAttribute("url", "managerIndex.jsp");
			}else {//普通职工
				map.put("url", "ordinaryIndex.jsp");
//				session.setAttribute("url", "ordinaryIndex.jsp");
			}
			map.put("userid", userid);
			map.put("deptname", user.getDeptname());
			map.put("rolename", user.getRolename());
		}
		else if("admin".equals(userid) && "admin".equals(pwd)) {
			map.put("msg", "2");
			map.put("url", "adminIndex.jsp");
			session.setAttribute("user", "admin");
		}
		else{
			String msg="账户或密码有误，请重试！";
			map.put("msg", msg);
//			response.getWriter().print(msg);
//			request.setAttribute("msg", msg);
//			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
		ObjectMapper mapper = new ObjectMapper();
		mapper.enable(SerializationFeature.INDENT_OUTPUT);	//序列化
		mapper.writeValue(response.getWriter(), map);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
